
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import '../utils/common_toast.dart';
import '../utils/dio_http.dart';
import './Index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: (Stack(
          alignment: Alignment.topCenter,
          children: <Widget>[
            Container(
              width: double.infinity,
              height: 450,
              child: Image.asset(
                "images/login.png",
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Text(
                        '苏州市高新区固危平衡试点项目',
                        style: TextStyle(color: Colors.white, fontSize: 24.0),
                      ),
                      Text(
                        '企业端',
                        style: TextStyle(color: Colors.white, fontSize: 14.0),
                      ),
                    ],
                  )
                  // Text(
                  //   ' 固危平衡试点项目',
                  //   style: TextStyle(color: Colors.white, fontSize: 24.0),
                  // )
                ],
              ),
              top: 110.0,
            ),
            Positioned(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '版权所有：苏州市伏泰信息科技股份有限公司',
                    style: TextStyle(color: Colors.grey, fontSize: 14.0),
                  ),
                ],
              ),
              bottom: 70.0,
            ),
            Align(
              alignment: Alignment(0.2, 0.1),
              child: Container(
                width: double.infinity,
                height: 300.0,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[LoginFrom()],
                ),
              ),
            ),
          ],
        )));

//      Container(
//      child: PageContent(name:'登录页'),
//    );
  }
}

class LoginFrom extends StatefulWidget {
  @override
  _LoginFromState createState() => _LoginFromState();
}

class _LoginFromState extends State<LoginFrom> {
  final _formKey = GlobalKey<FormState>();
  String userName = '';
  String password = '';
  // String companyId = '';
  String generateMd5(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    // 这里其实就是 digest.toString()
    return hex.encode(digest.bytes);
  }

  onLogin() async {
    // print(name.text);
    const url = '/wfgl/login/login';
    var params = {
      "loginName": userName,
      "passWord": generateMd5(password),
      "noVerifyCode": 'false'
    };
    var res = await DioHttp.of(context).post(url, params);
    var resString = json.decode(res.toString());
    print(resString);

    // SharedPreferences prefs = await SharedPreferences.getInstance();
    // prefs.setString('companyId', companyId);

    if (resString['rc'] == 0) {
      var companyId = resString['ret']['companyId'].toString();
      final prefs = await SharedPreferences.getInstance();
      prefs.setString('companyId', companyId);
      CommonToast.showToast('登录成功');
      Navigator.of(context).push(MaterialPageRoute(
        builder: (BuildContext context) {
          return Index();
        },
        settings: RouteSettings(
          arguments: {"companyId": companyId},
        ), // 传参
        fullscreenDialog: true,
      ));
    } else { CommonToast.showToast(resString['err']);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(40.0),
      child: Form(
        key: _formKey,
        child: Container(
          width: 350,
          margin: const EdgeInsets.fromLTRB(0, 50, 0, 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              TextFormField(
                decoration: const InputDecoration(
                    focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.blue),
                    ),
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey),
                    ),
                    prefixIcon: Icon(
                      Icons.supervised_user_circle,
                      color: Colors.blue,
                    ),
                    hintText: '请填写用户名',
                    hintStyle: TextStyle(fontSize: 12.0, color: Colors.grey)),
                validator: (value) {
                  if (value.isEmpty) {
                    return '用户名为必填参数!';
                  }
                  return null;
                },
                onChanged: (value) {
                  setState(() {
                    userName = value;
                  });
                },
              ),
              TextFormField(
                obscureText: true,
                decoration: const InputDecoration(
                    focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.blue),
                    ),
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey),
                    ),
                    prefixIcon: Icon(Icons.lock_open, color: Colors.blue),
                    hintText: '请填写密码',
                    hintStyle: TextStyle(fontSize: 12.0, color: Colors.grey)),
                validator: (value) {
                  if (value.isEmpty) {
                    return '密码为必填参数!';
                  }
                  return null;
                },
                onChanged: (value) {
                  setState(() {
                    password = value;
                  });
                },
              ),
              SizedBox(
                height: 20.0,
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      height: 35,
                      child: RaisedButton(
                        color: Colors.blue,
                        textColor: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                        onPressed: () {
                          // Validate will return true if the form is valid, or false if
                          // the form is invalid.
                          if (_formKey.currentState.validate()) {
                            print('${this.password}  ${this.userName}');
                            onLogin();
                          }
                        },
                        child: Text('确认登录'),
                      ),
                    ),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
